import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_soundmagus/util/util.dart';
import 'package:flutter_soundmagus/widget/alert/alert.dart';
import 'package:flutter_soundmagus/widget/alert/alert_define.dart';
import 'package:get/get.dart';

import '../save/save_controller.dart';

final kBluetoothNames = ['DSP88', 'PBX-DSP8', if (kDebugMode) 'DSP600.4D'];
// final kBluetoothNames = ['DSP8.8BT'];

typedef FlutterBlue = FlutterBluePlus;

class FlutterBlueApp extends StatefulWidget {
  @override
  _FlutterBlueAppState createState() => _FlutterBlueAppState();
}

typedef PageDevice = FlutterBlueApp;

class _FlutterBlueAppState extends State<FlutterBlueApp> {
  @override
  void initState() {
    super.initState();

    FlutterBlue.startScan(timeout: Duration(seconds: 4));
  }

  @override
  Widget build(BuildContext context) {
    return UnconstrainedBox(
        child: Material(
            color: Colors.transparent,
            child: Container(
                width: 480.w,
                height: Get.height - 80,
                decoration: kAlertBoxDecoration,
                clipBehavior: Clip.hardEdge,
                child: Column(children: [
                  Container(
                    alignment: Alignment.center,
                    height: 50,
                    child: Text(
                      'Devices',
                      style: TextStyle(fontSize: 20, color: Colors.white),
                    ),
                  ),
                  Expanded(
                    child: StreamBuilder<BluetoothAdapterState>(
                        stream: FlutterBlue.adapterState,
                        initialData: BluetoothAdapterState.unknown,
                        builder: (c, snapshot) {
                          final state = snapshot.data;
                          if (state == BluetoothAdapterState.on) {
                            return FindDevicesScreen();
                          }
                          return Container(
                            color: Colors.white,
                          );
                        }),
                  ),
                  Container(
                    height: 50,
                    child: Row(
                      children: [
                        Expanded(
                          child: TextButton(
                            onPressed: () async {
                              await FlutterBlue.stopScan();
                              FlutterBlue.startScan(timeout: Duration(seconds: 4));
                            },
                            child: Text(
                              'Refresh Device List',
                              style: TextStyle(fontSize: 20, color: Colors.white),
                            ),
                          ),
                        ),
                        VerticalDivider(
                          color: Colors.white,
                          width: 1,
                        ),
                        Expanded(
                          child: TextButton(
                            onPressed: () {
                              Get.dialog(AlertResetConfirm(
                                onPressed: (i) {
                                  if (i == 0) {
                                    //yes
                                    Get.find<SaveController>().resetDsp();
                                  }
                                  Get.back(result: i);
                                },
                              ));
                            },
                            child: Text(
                              'Reset DSP Tuning',
                              style: TextStyle(fontSize: 20, color: Colors.white),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ]))));
  }
}

class FindDevicesScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: () => FlutterBlue.startScan(timeout: Duration(seconds: 4)),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              StreamBuilder<List<ScanResult>>(
                stream: FlutterBlue.scanResults,
                initialData: [],
                builder: (c, snapshot) {
                  return FutureBuilder(
                      future: Future.value(FlutterBlue.connectedDevices),
                      builder: (c2, snapshot2) {
                        var ds = (snapshot.data!..removeWhere((e) => !kBluetoothNames.contains(e.device.platformName)))
                            .map((e) => e.device)
                            .toList();
                        if (snapshot2.data != null) {
                          final data = snapshot2.data!;
                          if (data.isNotEmpty) {
                            final device = data.first;
                            if (ds.firstWhereOrNull((element) => element.remoteId == device.remoteId) == null) {
                              ds.add(device); //已连接的加入显示（不知道为啥已连接的不会在扫描列表里）
                            }
                          }
                        }

                        return Column(
                          children: ds
                              .map((device) => ListTile(
                                    dense: true,
                                    title: Text(device.platformName),
                                    // subtitle: Text(r.device.id.toString()),
                                    trailing: StreamBuilder<BluetoothConnectionState>(
                                      stream: device.connectionState,
                                      initialData: BluetoothConnectionState.disconnected,
                                      builder: (c, snapshot) {
                                        var connected = snapshot.data == BluetoothConnectionState.connected;
                                        return IconButton(
                                          icon: connected ? 'device_on'.uiimg : 'device_off'.uiimg,
                                          onPressed: () {
                                            connected ? device.disconnect() : device.connect();
                                          },
                                        );
                                      },
                                    ),
                                  ))
                              .toList(),
                        );
                      });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
